package com.qztc.hire_end_core.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qztc.hire_end_core.mapper.BrandMapper;
import com.qztc.hire_end_dto.dto.Brand;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@CrossOrigin
@RequestMapping("/brand")
@Tag(name = "汉服品牌管理接口")
public class BrandController {
    @Autowired
    private BrandMapper brandMapper;

    @Operation(summary = "查询所有品牌")
    @GetMapping("/getAll")
    public List<Brand> getAll() {
        return new Brand().selectAll();
    }

    @Operation(summary = "根据brandId获取具体品牌")
    @GetMapping("/getbybrandId")
    public Brand getbybrandId(@RequestParam Integer brandId) {
        QueryWrapper<Brand> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("brand_id", brandId);
        return new Brand().selectOne(queryWrapper);
    }

    @Operation(summary = "根据brandId删除某一个具体品牌")
    @DeleteMapping("/delete")
    public boolean delete(@RequestBody Brand brand) {
        return brand.deleteById(brand.getBrandId());
    }

    @Operation(summary = "根据brandId修改某一个具体品牌")
    @PutMapping("/update")
    public boolean update(@RequestBody Brand brand) {
        return brand.updateById();
    }

    @Operation(summary = "增加品牌")
    @PostMapping("/add")
    public boolean add(@RequestBody Brand brand) {
        QueryWrapper<Brand> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("brand_name", brand.getBrandName());
        if(brand.selectCount(queryWrapper) > 0) {
            return false;
        }
        return brand.insert();
    }

    @Operation(summary = "批量删除品牌")
    @DeleteMapping("/deleteMany")
    public boolean deleteMany(@RequestBody List<Integer> brandIds) {
        if(brandIds.isEmpty() || brandIds == null){
            return false;
        }
        QueryWrapper<Brand> wrapper = new QueryWrapper<>();
        wrapper.in("brand_id", brandIds);
        return new Brand().delete(wrapper);
    }

    @Operation(summary = "批量增加品牌")
    @PostMapping("/addMany")
    public boolean addMany(@RequestBody List<Brand> brands) {
          if (brands.isEmpty() || brands == null) {
              return false;
          }
          QueryWrapper<Brand> queryWrapper = new QueryWrapper<>();
          queryWrapper.in("brand_name", brands.stream().map(Brand::getBrandName).collect(Collectors.toList()));
          if(brandMapper.selectCount(queryWrapper) > 0) {
              return false;
          }
          String sql = "insert into brand (brand_id, brand_name) values" +
                  brands.stream().map(brand -> String.format("(%d,'%s')", brand.getBrandId(), brand.getBrandName()))
                          .collect(Collectors.joining(","));
          return brandMapper.executeSql(sql);
    }
}
